<template>
  <div :class="Bem()">
    <!-- 加载中 -->
    <div v-if="isLoading">
      <i class="el-icon-loading" />
    </div>
    <!-- 没有图或首图加载失败 -->
    <span v-else-if="isError">
      <i class="el-icon-picture-outline" />
    </span>
    <img
      v-else
      loading="lazy"
      :class="Bem('image')"
      :src="imgSrc"
      v-bind="$attrs"
      v-on="$listeners"
    />
    <!-- 多张图 -->
    <div v-if="images.length > 1" :class="Bem('', 'more')">
      <span>+{{ images.length }}</span>
    </div>
  </div>
</template>

<script>
import { ImgUrl } from '@Components/assets/js/config'
import createBem from '@Components/assets/js/utils/bem'
import { tableNamespace } from '../config'

export default {
  props: {
    images: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      isLoading: true,
      isError: false,
      img: null,
      imgSrc: null
    }
  },
  watch: {
    images: {
      handler() {
        if (this.getSrc() !== this.imgSrc) {
          this.loadImage()
        }
      }
    }
  },
  created() {
    this.loadImage()
  },
  methods: {
    Bem: createBem(`${tableNamespace}__new-new-image`),
    loadImage() {
      const src = this.getSrc()
      if (!src) {
        this.handleError()
        return
      }
      this.isLoading = true
      this.isError = false
      this.img = new Image()
      this.img.onload = e => this.handleLoad(src)
      this.img.onerror = this.handleError.bind(this)
      this.img.src = src
    },
    handleLoad(src) {
      this.isLoading = false
      this.img = null
      this.imgSrc = src
    },
    handleError() {
      this.isError = true
      this.isLoading = false
      this.img = null
    },
    //获取第一张图
    getSrc() {
      const ignoreUrl = [ImgUrl + undefined, ImgUrl + null, ImgUrl]
      const imageList = this.images.filter(i => !ignoreUrl.includes(i))
      return imageList[0] || null
    }
  }
}
</script>

<style scoped lang="scss">
@import '../variables.scss';

.#{$TableNameSpace} {
  &__new-new-image {
    position: relative;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 25px;
    height: 25px;
    cursor: pointer;
    &--more {
      background-color: rgba($color: #000000, $alpha: 0.2);
      width: 100%;
      height: 100%;
      position: absolute;
      text-align: center;
      pointer-events: none;
      z-index: 1;
      span {
        color: #fff;
        -webkit-user-select: none;
      }
    }
    &__image {
      width: 100%;
      height: 100%;
      display: inline-block;
      object-fit: contain;
    }
  }
}
</style>
